package com.hqu.jim.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginFilter",urlPatterns = {"/com.hqu.jim/*"},initParams = {
        @WebInitParam(name = "encoding",value = "UTF-8"),
        @WebInitParam(name = "loginPage",value = "/login.jsp")
})
public class LoginFilter implements Filter {

    private FilterConfig filterConfig;

    private String encoding;

    private String loginPage;

    @Override
    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;

        this.encoding = filterConfig.getInitParameter(encoding);
        this.loginPage = filterConfig.getInitParameter(loginPage);

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //设置请求和响应的属性
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset="+encoding);

        //强转类型
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //判断会话域中是否有用户对象
        if (req.getSession().getAttribute("username")!=null) {
            chain.doFilter(request, response);
        }else {
            req.setAttribute("msg", "请先登录！");
            req.getRequestDispatcher(loginPage).forward(request, response);
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
